package com.xuanwu.ai.flow.component;

import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.dto.AuthDataDTO;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.sao.AIDetectSao;
import com.xuanwu.ai.flow.sao.req.AuthReq;
import com.xuanwu.ai.flow.utils.NodeDataUtils;
import com.xuanwu.ai.web.exception.BizException;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.HashMap;
import java.util.Map;

/**
 * 鉴权组件
 */
@LiteflowComponent(name = "AI鉴权组件", value = "authCmp")
@Slf4j
public class AuthCmp extends NodeComponent {

    @Autowired
    private AIDetectSao aiDetectSao;

    @Autowired
    @Qualifier("tenantTokenCache")
    private Cache<String, Map<String, String>> tenantTokenCache;

    @Override
    public void process() throws Exception {

        AuthDataDTO authData = this.getCmpData(AuthDataDTO.class);
        AuthReq authReq = new AuthReq(authData.getUsername(), authData.getPassword());
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);

        // 从缓存获取
        Map<String, String> tokenCacheMap = authReq.getUsername() != null ? tenantTokenCache.getIfPresent(authReq.getUsername()) : null;
        if (tokenCacheMap != null) {
            customContext.setTenantId(tokenCacheMap.get("tenantId"));
            customContext.setToken(tokenCacheMap.get("token"));
        } else {
            JSONObject jsonObject = aiDetectSao.aiAuth(authReq);

            if (jsonObject.get("status").equals(GlobalConstant.AUTH_FAIL)) {
                NodeDataUtils.setStepNodeData(customContext, authData.getUuid(), this.getName(), jsonObject);
                throw new BizException(ErrorCodeEnum.CMP_EXECUTE_FAIL, this.getName());
            }

            String token = jsonObject.getJSONObject("data").getString("token");
            String tenantId = String.valueOf(jsonObject.getJSONObject("data").getInteger("tenantId"));
            customContext.setToken(token);
            customContext.setTenantId(tenantId);

            tokenCacheMap = new HashMap<>();
            tokenCacheMap.put("tenantId", tenantId);
            tokenCacheMap.put("token", token);
            tenantTokenCache.put(authReq.getUsername(), tokenCacheMap);
        }

        JSONObject authInfo = new JSONObject();
        authInfo.put("data", tokenCacheMap);
        authInfo.put("status", GlobalConstant.AUTH_SUCCESS);
        NodeDataUtils.setStepNodeData(customContext, authData.getUuid(), this.getName(), authInfo);
    }

    @Override
    public boolean isEnd() {
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);
        return StringUtils.isEmpty(customContext.getToken());
    }


}
